package com.cuiweiyou.bluemesh.base;

import android.os.Handler;
import android.view.KeyEvent;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;

public abstract class ExitActivity extends BaseActivity {

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitByDoubleClick();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    // 标识是否退出
    boolean isExit = false;

    private void exitByDoubleClick() {
        Timer timer = null;
        if (!isExit) {
            isExit = true;
            Toast.makeText(ExitActivity.this, "再按一次退出", Toast.LENGTH_SHORT).show();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            }, 1000);
        } else {
            if (null != timer) {
                timer.cancel();
            }

            int exit = whenAppExit();

            if (0 == exit) {
                finish();

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        System.exit(0);
                    }
                }, 1000);
            } else {
                moveTaskToBack(false); // 进入后台
            }
        }
    }

    /**
     * 退出前收尾操作
     *
     * @return 0-没有特殊处理。其它-有特殊情况
     */
    public abstract int whenAppExit();
}


